package io.finer.erp.jeecg.bas.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.MaterialConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.UUID;
import io.finer.erp.jeecg.bas.dto.PrintProductDto;
import io.finer.erp.jeecg.bas.entity.BasCustomer;
import io.finer.erp.jeecg.bas.entity.BasCustomerAddress;
import io.finer.erp.jeecg.bas.entity.BasMaterial;
import io.finer.erp.jeecg.bas.entity.BasMaterialCategory;
import io.finer.erp.jeecg.bas.entity.BasMaterialTemp;
import io.finer.erp.jeecg.bas.entity.BasMeasureUnit;
import io.finer.erp.jeecg.bas.entity.SalesDelivery;
import io.finer.erp.jeecg.bas.entity.SalesDeliveryEntry;
import io.finer.erp.jeecg.bas.entity.ZrkDeliverEntry;
import io.finer.erp.jeecg.bas.entity.ZrkDeliveryMethod;
import io.finer.erp.jeecg.bas.entity.ZrkOrderProduct;
import io.finer.erp.jeecg.bas.entity.ZrkQzOrder;
import io.finer.erp.jeecg.bas.entity.ZrkShoporder;
import io.finer.erp.jeecg.bas.mapper.ZrkDeliverEntryMapper;
import io.finer.erp.jeecg.bas.service.IBasCustomerAddressService;
import io.finer.erp.jeecg.bas.service.IBasCustomerService;
import io.finer.erp.jeecg.bas.service.IBasMaterialCategoryService;
import io.finer.erp.jeecg.bas.service.IBasMaterialService;
import io.finer.erp.jeecg.bas.service.IBasMaterialTempService;
import io.finer.erp.jeecg.bas.service.IBasMeasureUnitService;
import io.finer.erp.jeecg.bas.service.ISalesDeliveryService;
import io.finer.erp.jeecg.bas.service.IZrkDeliverEntryService;
import io.finer.erp.jeecg.bas.service.IZrkDeliverService;
import io.finer.erp.jeecg.bas.service.IZrkDeliveryMethodService;
import io.finer.erp.jeecg.bas.service.IZrkOrderProductService;
import io.finer.erp.jeecg.bas.service.IZrkQzOrderService;
import io.finer.erp.jeecg.bas.service.IZrkShoporderService;
import io.finer.erp.jeecg.bas.vo.PrintOrderVO;
import io.finer.erp.jeecg.bas.vo.PrintProductVO;
import io.finer.erp.jeecg.stock.entity.StkIoBill;
import io.finer.erp.jeecg.stock.entity.StkIoBillEntry;
import io.finer.erp.jeecg.stock.entity.ZrkOrderProductMaterialLk;
import io.finer.erp.jeecg.stock.service.IStkIoBillEntryService;
import io.finer.erp.jeecg.stock.service.IStkIoBillService;
import io.finer.erp.jeecg.stock.service.IZrkOrderProductMaterialLkService;

/**
 * @Description: 出货单对应出货明细表
 * @Author: jeecg-boot
 * @Date:   2020-10-21
 * @Version: V1.0
 */
@Service
public class ZrkDeliverEntryServiceImpl extends ServiceImpl<ZrkDeliverEntryMapper, ZrkDeliverEntry> implements IZrkDeliverEntryService {
	
	@Autowired
	private ZrkDeliverEntryMapper zrkDeliverEntryMapper;
	@Autowired
	private IZrkDeliverService deliverService;
	@Autowired
	private IZrkDeliveryMethodService deliveryMethodService;
	@Autowired
	private IZrkShoporderService orderService;
	@Autowired
	private IZrkOrderProductService productService;
	@Autowired
	private IBasCustomerService customerService;
	@Autowired
	private IBasMaterialCategoryService categoryService;
	@Autowired
	private IBasMeasureUnitService unitService;
	@Autowired
    private IStkIoBillEntryService stkIoBillService;
	@Autowired
    private IStkIoBillService ioBillService;
	@Autowired
    private IBasCustomerAddressService customerAddressService;
	@Autowired
    private IBasMaterialService materialService;
	@Autowired
    private ISalesDeliveryService deliveryService;
	@Autowired
    private ISysBaseAPI sysBaseAPI;
	@Autowired
	private IBasMaterialTempService tempService;
	@Autowired
	private IZrkQzOrderService mesService;
	@Autowired
	private IZrkOrderProductMaterialLkService productMateiralLkService;

	// 大写数字
    private static final String[] NUMBERS = {"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"};
    // 整数部分的单位
    private static final String[] IUNIT = {"元","拾","佰","仟","万","拾","佰","仟","亿","拾","佰","仟","万","拾","佰","仟"};
    // 小数部分的单位
    private static final String[] DUNIT = {"角","分","厘"};

	
	@Override
	public List<ZrkDeliverEntry> selectByMainId(String mainId) {
		return zrkDeliverEntryMapper.selectByMainId(mainId);
	}

	@Override
	public Result<?> printDeliver(String id) {
		// TODO Auto-generated method stub
		ZrkShoporder zrkShoporder = orderService.getById(id);
//		zrkShoporder.getCustomerMobile();
		PrintOrderVO printOrderVO = new PrintOrderVO();
		printOrderVO.setCustomerAddress(zrkShoporder.getCustomerAddress());
		printOrderVO.setCustomerName(zrkShoporder.getCustomerName());
		printOrderVO.setCustomerPhone(zrkShoporder.getCustomerMobile());
		BasCustomer customer = customerService.getById("1318447754322341890");
		printOrderVO.setSelfAddress(customer.getAddress());
		printOrderVO.setSelfPhone(customer.getCorporatePhone());
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		printOrderVO.setMaker(sysUser.getRealname());
		
		BigDecimal total = BigDecimal.ZERO;
		List<PrintProductVO> list = CollUtil.newArrayList();
		List<ZrkOrderProduct> products = productService.selectByMainId(zrkShoporder.getId());
		for (ZrkOrderProduct product : products) {
			PrintProductVO vo = new PrintProductVO();
			String materialId = product.getMaterialId();
			BasMaterialCategory category = categoryService.getById(materialId);
			vo.setProductName(category.getName());
			vo.setModel(product.getProductSpecs());
			BigDecimal totalPrice = product.getTotalPrice();
			if(null != totalPrice) {
				totalPrice = totalPrice.setScale(2, BigDecimal.ROUND_DOWN);
				vo.setTotalPrice(totalPrice);
				total = total.add(totalPrice);
			}
			BigDecimal unitPrice = product.getUnitPrice();
			if(null != unitPrice) {
				unitPrice = unitPrice.setScale(2, BigDecimal.ROUND_DOWN);
				vo.setUnitPrice(unitPrice.toString());
			}
			vo.setRemark(product.getRemark());
			vo.setViceQty(product.getProductCount().setScale(0, BigDecimal.ROUND_DOWN));
			String unitId = category.getUnitId();
			if(StringUtils.isNotBlank(unitId)) {
				BasMeasureUnit unit = this.unitService.getById(unitId);
				if(null != unit) {
					vo.setUnit(unit.getName());
				}
			}
			String processId = product.getProcessId();
			if(MaterialConstant.PROCESS_COMPOUND.equals(processId)) {
				vo.setViceUnit("卷");
			}
			if(MaterialConstant.PROCESS_PART.equals(processId)) {
				vo.setViceUnit("卷");
			}
			if(MaterialConstant.PROCESS_CUTTING_BIG.equals(processId) || MaterialConstant.PROCESS_CUTTING_NORMAL.equals(processId)) {
				vo.setViceUnit("张");
			}
			
			if(null != totalPrice && null != unitPrice) {
				BigDecimal qty = totalPrice.divide(unitPrice, 2, BigDecimal.ROUND_HALF_DOWN);
				vo.setQty(qty);
			}
			list.add(vo);
		}
		printOrderVO.setList(list);
		total = total.setScale(2, BigDecimal.ROUND_HALF_UP);
		printOrderVO.setTotalAmount(total.toString());
		printOrderVO.setTotalBig(toChinese(total.toString()));
		return Result.ok(printOrderVO);
	}

    @Override
    public PrintOrderVO Ddprint(String code) {
        List<StkIoBill> ioBills = ioBillService.getBillBySourceCode(code);
        PrintOrderVO printOrderVO = new PrintOrderVO();//打印vo
        SalesDelivery salesVo = new SalesDelivery();//出库信息保存vo
        List<PrintProductVO> list = CollUtil.newArrayList();
        List<SalesDeliveryEntry> entries = CollUtil.newArrayList();
        BigDecimal totals = new BigDecimal("0");
        ZrkShoporder order = this.orderService.lambdaQuery().eq(ZrkShoporder::getOrderNo, code).one();
        List<ZrkOrderProduct> orderItemList = Lists.newArrayList();
        if(null != order) {
        	
        }
        salesVo.setSourceCode(order.getOrderNo());
        for (StkIoBill ioBill : ioBills) {

            BasCustomer customer = new BasCustomer();
            List<BasCustomerAddress> address = Lists.newArrayList();
            if (ioBill != null) {
                customer = customerService.getById(ioBill.getCustomerId());
            }
            if (customer != null) {
                address = customerAddressService.selectAddressByCustomerId(customer.getId());
            }
            if (address == null || address.size() < 1) {
                System.out.println("没有找到到客户地址");
            }
            BasCustomer customer1 = customerService.getById("1318447754322341890");
            LambdaQueryWrapper<StkIoBillEntry> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(StkIoBillEntry::getMid, ioBill.getId());
            List<StkIoBillEntry> stkIoBills = stkIoBillService.list(wrapper);
            BigDecimal total = BigDecimal.ZERO;
            ZrkShoporder zrkShoporder = orderService.selectByOrderCode(ioBill.getSourceNo());
            List<ZrkOrderProduct> zrkOrderProduct = productService.selectByMainId(zrkShoporder.getId());
            if (address != null && address.size() > 0) {
                printOrderVO.setCustomerAddress(address.get(0).getAddress());
                printOrderVO.setCustomerPhone(address.get(0).getPhoneNo());
                salesVo.setCustomerAddress(address.get(0).getAddress());
                salesVo.setCustomerPhone(address.get(0).getPhoneNo());
            }
            if(null != zrkShoporder) {
            	printOrderVO.setCustomerPhone(zrkShoporder.getCustomerMobile());
            	if(StringUtils.isBlank(printOrderVO.getCustomerAddress())) {
            		printOrderVO.setCustomerAddress(zrkShoporder.getCustomerAddress());
            	}
            }
//            printOrderVO.setCode(zrkShoporder.getOrderNo());
            printOrderVO.setCustomerName(customer.getName());
            printOrderVO.setDateString(DateUtils.formatDate(new Date(), "yyyy/MM/dd"));
            printOrderVO.setSelfAddress(customer1.getAddress());
            printOrderVO.setSelfPhone(customer1.getCorporatePhone());

            salesVo.setCompanyId(customer1.getId());
            salesVo.setCustomerName(customer.getName());
            salesVo.setCustomerId(customer.getId());
            salesVo.setShippingDate(new Date());
            salesVo.setSelfAddress(customer1.getAddress());
            salesVo.setSelfPhone(customer1.getCorporatePhone());
//            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//            printOrderVO.setMaker(sysUser.getRealname());
//            salesVo.setMaker(sysUser.getRealname());
            /***********测试用***********/
//            printOrderVO.setMaker("admin");
//            salesVo.setMaker("admin");
            /*****************/
            Map<PrintProductVO, List<BasMaterial>> map = Maps.newHashMap();
            Map<String, StkIoBillEntry> entryMap = Maps.newHashMap();
            for (StkIoBillEntry stkIoBill : stkIoBills) {
                PrintProductVO vo = new PrintProductVO();//打印vo
                String materialId = stkIoBill.getMaterialId();
                BasMaterial basMaterial = materialService.getById(materialId);
                vo.setProductName(basMaterial.getName());
                String[] s = basMaterial.getModel().split("\\*");
                StringBuffer str = new StringBuffer(StringUtils.EMPTY);
                if(s.length > 1) {
                	String l = new BigDecimal(s[0]).stripTrailingZeros().toPlainString();
                    String w = new BigDecimal(s[1]).stripTrailingZeros().toPlainString();
                    str.append(l);
                    str.append("*");
                    str.append(w);
                } else {
                	String l = new BigDecimal(s[0]).stripTrailingZeros().toPlainString();
                	str.append(l);
                }
                vo.setModel(str.toString());
                vo.setRemark(stkIoBill.getRemark());
                if (map.get(vo) == null) {
                    List<BasMaterial> basMaterials = Lists.newArrayList();
                    basMaterials.add(basMaterial);
                    map.put(vo, basMaterials);
                } else {
                    map.get(vo).add(basMaterial);
                }
                entryMap.put(materialId, stkIoBill);
            }

            for (PrintProductVO vo : map.keySet()) {
                SalesDeliveryEntry entry = new SalesDeliveryEntry();//
                List<BasMaterial> basMaterials = map.get(vo);

                BigDecimal price = BigDecimal.ZERO;
                BigDecimal viceQty = BigDecimal.ZERO;
                BigDecimal qtys = BigDecimal.ZERO;
                Integer count = 0;
                String categoryId="";
                for (int i = 0; i < basMaterials.size(); i++) {
                    BasMaterial material = basMaterials.get(i);
                    categoryId=material.getCategoryId();
                    String materialId = material.getId();
                    StkIoBillEntry stkIoBillEntry = entryMap.get(materialId);
                    BigDecimal totalPrice = stkIoBillEntry.getSettleAmt();
                    if (null != totalPrice) {
                        price = price.add(totalPrice);
                        vo.setTotalPrice(totalPrice);
                        entry.setTotalPrice(totalPrice);
                        total = total.add(totalPrice);
                    }
                    BigDecimal unitPrice = stkIoBillEntry.getSettlePrice();
                    if (null != unitPrice) {
                        vo.setUnitPrice(unitPrice.setScale(2, BigDecimal.ROUND_DOWN).toString());
                        entry.setUnitPrice(unitPrice.setScale(2, BigDecimal.ROUND_DOWN).toString());
                    }
                    BigDecimal vqty = basMaterials.get(i).getViceQuantity();
                    viceQty = viceQty.add(vqty);
                    vo.setViceQty(basMaterials.get(i).getViceQuantity().setScale(0, BigDecimal.ROUND_DOWN));
                    String unitId = basMaterials.get(i).getUnitId();
                    if (StringUtils.isNotBlank(unitId)) {
                        BasMeasureUnit unit = this.unitService.getById(unitId);
                        if (null != unit) {
                            vo.setUnit(unit.getName());
                            entry.setUnit(unit.getName());
                        }
                    }
                    String processId = null;
                    if (zrkOrderProduct != null && zrkOrderProduct.size() > 0) {
                        processId = zrkOrderProduct.get(0).getProcessId();
                    }
                    if (MaterialConstant.PROCESS_COMPOUND.equals(processId)) {
                        vo.setViceUnit("卷");
                        entry.setViceUnit("卷");
                    }
                    if (MaterialConstant.PROCESS_PART.equals(processId)) {
                        vo.setViceUnit("卷");
                        entry.setViceUnit("卷");
                    }
                    if (MaterialConstant.PROCESS_CUTTING_BIG.equals(processId) || MaterialConstant.PROCESS_CUTTING_NORMAL.equals(processId)) {
                        vo.setViceUnit("张");
                        entry.setViceUnit("张");
                    }
                    BigDecimal inventoryQty = stkIoBillEntry.getSettleQty();
                    if (!inventoryQty.equals(BigDecimal.ZERO)) {
                        qtys = qtys.add(inventoryQty);
                    }
                    ++count;
                }

                vo.setTotalPrice(price.setScale(2, BigDecimal.ROUND_DOWN));
                vo.setQty(qtys);
                vo.setViceQty(viceQty.setScale(2, BigDecimal.ROUND_DOWN));
                vo.setCount(count);
                list.add(vo);

                entry.setModel(vo.getModel());
                entry.setRemark(vo.getRemark());
                entry.setProductName(vo.getProductName());
                entry.setCategoryId(categoryId);
                entry.setTotalPrice(price.setScale(2, BigDecimal.ROUND_DOWN));
                entry.setQty(qtys);
                entry.setViceQty(viceQty.setScale(2, BigDecimal.ROUND_DOWN));
                entry.setCount(count);
                entry.setWriteAmount(BigDecimal.ZERO);
                entry.setWriteStatus("0");
                entries.add(entry);
            }
            if (StringUtils.isNotBlank(zrkShoporder.getExpressType())) {
                printOrderVO.setHyType(zrkShoporder.getExpressType());
                salesVo.setHyType(zrkShoporder.getExpressType());
            }
            if (StringUtils.isNotBlank(zrkShoporder.getPayType())) {
                printOrderVO.setPayType(zrkShoporder.getPayType());
            }
            totals = totals.add(total).setScale(2, BigDecimal.ROUND_HALF_UP);
            ioBill.setIsPrint(1);
            ioBillService.updateById(ioBill);
        }
        if (StringUtils.isNotBlank(printOrderVO.getHyType())) {
        	ZrkDeliveryMethod zrkDeliveryMethod = deliveryMethodService.getById(printOrderVO.getHyType());
            if(zrkDeliveryMethod!=null) {
            	printOrderVO.setHyType(zrkDeliveryMethod.getName());
            }
        }
        if (StringUtils.isNotBlank(printOrderVO.getPayType())) {
        	List<DictModel> modelList = sysBaseAPI.queryDictItemsByCode("sale_order_pay_type");
        	String payType = "";
        	if(modelList!=null&&modelList.size()>0) {
        		for(DictModel model:modelList) {
        			model.getValue();
        			if(model.getValue().equals(printOrderVO.getPayType())) {
        				payType = model.getText();
        			}
        		}
        	}
            printOrderVO.setPayType(payType);
        }
        printOrderVO.setTotalAmount(totals.toString());
        printOrderVO.setTotalBig(toChinese(totals.toString()));
        salesVo.setTotalAmount(totals);
        salesVo.setTotalBig(toChinese(totals.toString()));
        salesVo.setSalesType(0);
        printOrderVO.setList(list);
        if(StringUtils.isNotBlank(salesVo.getCustomerName())){
            deliveryService.saveMach(salesVo, entries, null);
        }
        printOrderVO.setCode(salesVo.getCode());

        return printOrderVO;
    }



    @Override
    public List<PrintProductVO> getBillEntryByBillNo(String billNo,String billType) {
        StkIoBill ioBill = ioBillService.getBillByOrderNo(billNo);
        ZrkShoporder zrkShoporder = orderService.selectByOrderCode(ioBill.getSourceNo());
        List<ZrkOrderProduct> zrkOrderProduct = productService.selectByMainId(zrkShoporder.getId());
        LambdaQueryWrapper<StkIoBillEntry> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StkIoBillEntry::getBillNo, ioBill.getBillNo());
        List<StkIoBillEntry> stkIoBills = stkIoBillService.list(wrapper);
        BigDecimal total = BigDecimal.ZERO;
        List<PrintProductVO> list = CollUtil.newArrayList();
        Map<PrintProductVO, List<BasMaterial>> map = Maps.newHashMap();
        Map<PrintProductVO, List<BasMaterialCategory>> map1 = Maps.newHashMap();
        Map<String, StkIoBillEntry> entryMap = Maps.newHashMap();
        for (StkIoBillEntry stkIoBill : stkIoBills) {
            PrintProductVO vo = new PrintProductVO();
            String materialId = stkIoBill.getMaterialId();
            BasMaterial basMaterial = materialService.getById(materialId);
            vo.setProductName(basMaterial.getName());
            vo.setModel(basMaterial.getModel());
            vo.setRemark(stkIoBill.getRemark());
            if (map.get(vo) == null) {
                List<BasMaterial> basMaterials = Lists.newArrayList();
                basMaterials.add(basMaterial);
                map.put(vo, basMaterials);
            } else {
                map.get(vo).add(basMaterial);
            }
            entryMap.put(materialId, stkIoBill);
        }
        for (PrintProductVO vo : map.keySet()) {
            List<BasMaterial> basMaterials = map.get(vo);
            BigDecimal price = BigDecimal.ZERO;
            BigDecimal viceQty = BigDecimal.ZERO;
            BigDecimal qtys = BigDecimal.ZERO;
            Integer count = 0;
            for (int i = 0; i < basMaterials.size(); i++) {
                BasMaterial material = basMaterials.get(i);
                String materialId = material.getId();
                StkIoBillEntry stkIoBillEntry = entryMap.get(materialId);
                BigDecimal totalPrice = stkIoBillEntry.getSettleAmt();
                if (null != totalPrice) {
                    price = price.add(totalPrice);
                    vo.setTotalPrice(totalPrice);
                    total = total.add(totalPrice);
                }
                BigDecimal unitPrice = stkIoBillEntry.getSettlePrice();
                if (null != unitPrice) {
                    vo.setUnitPrice(unitPrice.setScale(2, BigDecimal.ROUND_DOWN).toString());
                }
                BigDecimal vqty = basMaterials.get(i).getViceQuantity();
                viceQty = viceQty.add(vqty);
                vo.setViceQty(basMaterials.get(i).getViceQuantity().setScale(0, BigDecimal.ROUND_DOWN));
                String unitId = basMaterials.get(i).getUnitId();
                if (StringUtils.isNotBlank(unitId)) {
                    BasMeasureUnit unit = this.unitService.getById(unitId);
                    if (null != unit) {
                        vo.setUnit(unit.getName());
                    }
                }
                String processId = null;
                if (zrkOrderProduct != null && zrkOrderProduct.size() > 0) {
                    processId = zrkOrderProduct.get(0).getProcessId();
                }
                if (MaterialConstant.PROCESS_COMPOUND.equals(processId)) {
                    vo.setViceUnit("卷");
                }
                if (MaterialConstant.PROCESS_PART.equals(processId)) {
                    vo.setViceUnit("卷");
                }
                if (MaterialConstant.PROCESS_CUTTING_BIG.equals(processId) || MaterialConstant.PROCESS_CUTTING_NORMAL.equals(processId)) {
                    vo.setViceUnit("张");
                }
                BigDecimal inventoryQty = stkIoBillEntry.getSettleQty();
                if (!inventoryQty.equals(BigDecimal.ZERO)) {
                    qtys = qtys.add(inventoryQty);
                }
                ++count;
            }
            vo.setTotalPrice(price.setScale(2, BigDecimal.ROUND_DOWN));
            vo.setQty(qtys);
            vo.setViceQty(viceQty.setScale(2, BigDecimal.ROUND_DOWN));
            vo.setCount(count);
            list.add(vo);
        }
        return list;
    }



    @Override
    public List<PrintProductDto> exportIoBill(String billNo) {

        return null;
    }



    /**
     *  转换为大写的中文金额
     * @param str 字符串类型的 金额数字
     * @return
     */
    public static String toChinese(String str) {
        // 判断输入的金额字符串是否符合要求
        if (StringUtils.isBlank(str) || !str.matches("(-)?[\\d]*(.)?[\\d]*")) {
            return "抱歉，请输入数字！";
        }
 
        if("0".equals(str) || "0.00".equals(str) || "0.0".equals(str)) {
            return "零元";
        }
 
        // 判断金额数字中是否存在负号"-"
        boolean flag = false;
        if(str.startsWith("-")){
            // 标志位，标志此金额数字为负数
            flag = true;
            str = str.replaceAll("-", "");
        }
 
        // 去掉金额数字中的逗号","
        str = str.replaceAll(",", "");
        String integerStr;//整数部分数字
        String decimalStr;//小数部分数字
 
        // 初始化：分离整数部分和小数部分
        if(str.indexOf(".")>0) {
            integerStr = str.substring(0,str.indexOf("."));
            decimalStr = str.substring(str.indexOf(".") + 1);
        }else if(str.indexOf(".")==0) {
            integerStr = "";
            decimalStr = str.substring(1);
        }else {
            integerStr = str;
            decimalStr = "";
        }
 
        // beyond超出计算能力，直接返回
        if(integerStr.length()>IUNIT.length) {
            return "超出计算能力！";
        }
 
        // 整数部分数字
        int[] integers = toIntArray(integerStr);
        // 判断整数部分是否存在输入012的情况
        if (integers.length>1 && integers[0] == 0) {
            return "抱歉，输入数字不符合要求！";
        }
        // 设置万单位
        boolean isWan = isWan5(integerStr);
        // 小数部分数字
        int[] decimals = toIntArray(decimalStr);
        // 返回最终的大写金额
        String result = getChineseInteger(integers, isWan) + getChineseDecimal(decimals);
        if(flag){
            // 如果是负数，加上"负"
            return "负" + result;
        }else{
            return result;
        }
    }
 
    /**
     *  将字符串转为int数组
     * @param number  数字
     * @return
     */
    private static int[] toIntArray(String number) {
        int[] array = new int[number.length()];
        for(int i = 0;i<number.length();i++) {
            array[i] = Integer.parseInt(number.substring(i,i+1));
        }
        return array;
    }
 
    /**
     *  将整数部分转为大写的金额
     * @param integers 整数部分数字
     * @param isWan  整数部分是否已经是达到【万】
     * @return
     */
    public static String getChineseInteger(int[] integers,boolean isWan) {
        StringBuffer chineseInteger = new StringBuffer("");
        int length = integers.length;
        if (length == 1 && integers[0] == 0) {
            return "";
        }
        for(int i=0; i<length; i++) {
            String key = "";
            if(integers[i] == 0) {
                if((length - i) == 13)//万（亿）
                    key = IUNIT[4];
                else if((length - i) == 9) {//亿
                    key = IUNIT[8];
                }else if((length - i) == 5 && isWan) {//万
                    key = IUNIT[4];
                }else if((length - i) == 1) {//元
                    key = IUNIT[0];
                }
                if((length - i)>1 && integers[i+1]!=0) {
                    key += NUMBERS[0];
                }
            }
            chineseInteger.append(integers[i]==0?key:(NUMBERS[integers[i]]+IUNIT[length - i -1]));
        }
        return chineseInteger.toString();
    }
 
    /**
     *  将小数部分转为大写的金额
     * @param decimals 小数部分的数字
     * @return
     */
    private static String getChineseDecimal(int[] decimals) {
        StringBuffer chineseDecimal = new StringBuffer("");
        for(int i = 0;i<decimals.length;i++) {
            if(i == 3) {
                break;
            }
            chineseDecimal.append(decimals[i]==0?"":(NUMBERS[decimals[i]]+DUNIT[i]));
        }
        return chineseDecimal.toString();
    }
 
    /**
     *  判断当前整数部分是否已经是达到【万】
     * @param integerStr  整数部分数字
     * @return
     */
    private static boolean isWan5(String integerStr) {
        int length = integerStr.length();
        if(length > 4) {
            String subInteger = "";
            if(length > 8) {
                subInteger = integerStr.substring(length- 8,length -4);
            }else {
                subInteger = integerStr.substring(0,length - 4);
            }
            return Integer.parseInt(subInteger) > 0;
        }else {
            return false;
        }
    }
    public static void main(String[] args) {
    	String number = "148554772.56";
        System.out.println(number+": "+toChinese(number));

        String number1 = "0";
        System.out.println(number1+": "+toChinese(number1));
	}

	@Override
	public PrintOrderVO DdIoBillPrint(String billId) {
		StkIoBill bill = ioBillService.getById(billId);
		List<StkIoBill> ioBills = Lists.newArrayList();
		if(null != bill) {
			ioBills.add(bill);
		}
        PrintOrderVO printOrderVO = new PrintOrderVO();//打印vo
        SalesDelivery salesVo = new SalesDelivery();//出库信息保存vo
        List<PrintProductVO> list = CollUtil.newArrayList();
        List<SalesDeliveryEntry> entries = CollUtil.newArrayList();
        BigDecimal totals = new BigDecimal("0");
        List<ZrkOrderProduct> orderItemList = Lists.newArrayList();
        for (StkIoBill ioBill : ioBills) {
            BasCustomer customer = null;
            List<BasCustomerAddress> address = Lists.newArrayList();
            if (ioBill != null) {
                customer = customerService.getById(ioBill.getCustomerId());
            }
            LambdaQueryWrapper<StkIoBillEntry> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(StkIoBillEntry::getMid, ioBill.getId());
            List<StkIoBillEntry> billEntryList = stkIoBillService.list(wrapper);
            if(null == billEntryList) {
            	billEntryList = Lists.newArrayList();
            }
            List<String> materialIdList = Lists.newArrayList(UUID.randomUUID().toString());
            for (StkIoBillEntry entry : billEntryList) {
            	materialIdList.add(entry.getMaterialId());
			}
            List<ZrkOrderProductMaterialLk> lkList = this.productMateiralLkService.listByIds(materialIdList);
            List<String> productIdList = Lists.newArrayList(UUID.randomUUID().toString());
            for (ZrkOrderProductMaterialLk lk : lkList) {
            	productIdList.add(lk.getProductId());
			}
            List<ZrkOrderProduct> productList = this.productService.listByIds(productIdList);
            ZrkShoporder order = null;
            if(CollUtil.isNotEmpty(productList)) {
            	ZrkOrderProduct zrkOrderProduct = productList.get(0);
            	String orderId = zrkOrderProduct.getOrderId();
            	ZrkShoporder shoporder = this.orderService.getById(orderId);
            	if(null != shoporder) {
            		order = shoporder;
            	}
            }
            if(order != null) {
            	salesVo.setSourceCode(order.getOrderNo());
            }
            
            if (customer != null) {
                address = customerAddressService.selectAddressByCustomerId(customer.getId());
            }
            if(null == customer) {
            	customer = new BasCustomer();
            }
//            if (address == null || address.size() < 1) {
//                System.out.println("没有找到到客户地址");
//            }
            BasCustomer customer1 = customerService.getById("1318447754322341890");//查询到启元的公司信息
            BigDecimal total = BigDecimal.ZERO;
//            ZrkShoporder zrkShoporder = orderService.selectByOrderCode(ioBill.getSourceNo());
//            List<ZrkOrderProduct> zrkOrderProduct = productService.selectByMainId(zrkShoporder.getId());
            if (address != null && !address.isEmpty()) {
                printOrderVO.setCustomerAddress(address.get(0).getAddress());
                printOrderVO.setCustomerPhone(address.get(0).getPhoneNo());
                salesVo.setCustomerAddress(address.get(0).getAddress());
                salesVo.setCustomerPhone(address.get(0).getPhoneNo());
            }
            if(null != order) {
            	printOrderVO.setCustomerPhone(order.getCustomerMobile());
            	if(StringUtils.isBlank(printOrderVO.getCustomerAddress())) {
            		printOrderVO.setCustomerAddress(order.getCustomerAddress());
            	}
            	printOrderVO.setCode(order.getOrderNo());
            }
            printOrderVO.setCustomerName(customer.getName());
            printOrderVO.setDateString(DateUtils.formatDate(new Date(), "yyyy/MM/dd"));
            printOrderVO.setSelfAddress(customer1.getAddress());
            printOrderVO.setSelfPhone(customer1.getCorporatePhone());

            salesVo.setCompanyId(customer1.getId());
            salesVo.setCustomerName(customer.getName());
            salesVo.setCustomerId(customer.getId());
            salesVo.setShippingDate(new Date());
            salesVo.setSelfAddress(customer1.getAddress());
            salesVo.setSelfPhone(customer1.getCorporatePhone());
//            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//            printOrderVO.setMaker(sysUser.getRealname());
//            salesVo.setMaker(sysUser.getRealname());
            /***********测试用***********/
//            printOrderVO.setMaker("admin");
//            salesVo.setMaker("admin");
            /*****************/
            Map<PrintProductVO, List<BasMaterial>> map = Maps.newHashMap();
            Map<String, StkIoBillEntry> entryMap = Maps.newHashMap();
            for (StkIoBillEntry stkIoBill : billEntryList) {
                PrintProductVO vo = new PrintProductVO();//打印vo
                String materialId = stkIoBill.getMaterialId();
                BasMaterial basMaterial = materialService.getById(materialId);
                vo.setProductName(basMaterial.getName());
                String[] s = basMaterial.getModel().split("\\*");
                StringBuffer str = new StringBuffer(StringUtils.EMPTY);
                if(s.length > 1) {
                	String l = new BigDecimal(s[0]).stripTrailingZeros().toPlainString();
                    String w = new BigDecimal(s[1]).stripTrailingZeros().toPlainString();
                    str.append(l);
                    str.append("*");
                    str.append(w);
                } else {
                	String l = new BigDecimal(s[0]).stripTrailingZeros().toPlainString();
                	str.append(l);
                }
                vo.setModel(str.toString());
                vo.setRemark(stkIoBill.getRemark());
                if (map.get(vo) == null) {
                    List<BasMaterial> basMaterials = Lists.newArrayList();
                    basMaterials.add(basMaterial);
                    map.put(vo, basMaterials);
                } else {
                    map.get(vo).add(basMaterial);
                }
                entryMap.put(materialId, stkIoBill);
            }
            Map<String, BasMaterialTemp> tempMap = Maps.newHashMap();
            for (PrintProductVO vo : map.keySet()) {
                SalesDeliveryEntry entry = new SalesDeliveryEntry();//
                List<BasMaterial> basMaterials = map.get(vo);
                List<String> materialCodeList = Lists.newArrayList(UUID.randomUUID().toString());
                if(CollUtil.isNotEmpty(basMaterials)) {
                	for(BasMaterial material : basMaterials) {
                		materialCodeList.add(material.getCode());
                	}
                }
                List<BasMaterialTemp> tempList = tempService.getByCodes(materialCodeList);
                for (BasMaterialTemp temp : tempList) {
					tempMap.put(temp.getCode(), temp);
				}
                BigDecimal price = BigDecimal.ZERO;
                BigDecimal viceQty = BigDecimal.ZERO;
                BigDecimal qtys = BigDecimal.ZERO;
                Integer count = 0;
                String categoryId="";
                for (int i = 0; i < basMaterials.size(); i++) {
                    BasMaterial material = basMaterials.get(i);
                    categoryId=material.getCategoryId();
                    String materialId = material.getId();
                    StkIoBillEntry stkIoBillEntry = entryMap.get(materialId);
                    BigDecimal totalPrice = stkIoBillEntry.getSettleAmt();
                    if (null != totalPrice) {
                        price = price.add(totalPrice);
                        vo.setTotalPrice(totalPrice);
                        entry.setTotalPrice(totalPrice);
                        total = total.add(totalPrice);
                    }
                    BigDecimal unitPrice = stkIoBillEntry.getSettlePrice();
                    if (null != unitPrice) {
                        vo.setUnitPrice(unitPrice.setScale(2, BigDecimal.ROUND_DOWN).toString());
                        entry.setUnitPrice(unitPrice.setScale(2, BigDecimal.ROUND_DOWN).toString());
                    }
                    BigDecimal vqty = basMaterials.get(i).getViceQuantity();
                    viceQty = viceQty.add(vqty);
                    vo.setViceQty(basMaterials.get(i).getViceQuantity().setScale(0, BigDecimal.ROUND_DOWN));
                    String unitId = basMaterials.get(i).getUnitId();
                    if (StringUtils.isNotBlank(unitId)) {
                        BasMeasureUnit unit = this.unitService.getById(unitId);
                        if (null != unit) {
                            vo.setUnit(unit.getName());
                            entry.setUnit(unit.getName());
                        }
                    }
                    BasMaterialTemp temp = tempMap.get(material.getCode());
                    String processId = null;
                    if(null != temp) {
                    	String procedureId = temp.getProcedureId();
                    	if(StringUtils.isNotBlank(procedureId)) {
                    		ZrkQzOrder mes = this.mesService.getById(procedureId);
                    		if(null != mes) {
                    			processId = mes.getProcessId();
                    		}
                    	}
                    }
                    
//                    if (zrkOrderProduct != null && zrkOrderProduct.size() > 0) {
//                        processId = zrkOrderProduct.get(0).getProcessId();
//                    }
                    if (MaterialConstant.PROCESS_COMPOUND.equals(processId)) {
                        vo.setViceUnit("卷");
                        entry.setViceUnit("卷");
                    }
                    if (MaterialConstant.PROCESS_PART.equals(processId)) {
                        vo.setViceUnit("卷");
                        entry.setViceUnit("卷");
                    }
                    if (MaterialConstant.PROCESS_CUTTING_BIG.equals(processId) || MaterialConstant.PROCESS_CUTTING_NORMAL.equals(processId)) {
                        vo.setViceUnit("张");
                        entry.setViceUnit("张");
                    }
                    if(null == processId) {
                    	vo.setViceUnit("卷");
                        entry.setViceUnit("卷");
                    }
                    BigDecimal inventoryQty = stkIoBillEntry.getSettleQty();
                    if (!inventoryQty.equals(BigDecimal.ZERO)) {
                        qtys = qtys.add(inventoryQty);
                    }
                    ++count;
                }

                vo.setTotalPrice(price.setScale(2, BigDecimal.ROUND_DOWN));
                vo.setQty(qtys);
                vo.setViceQty(viceQty.setScale(2, BigDecimal.ROUND_DOWN));
                vo.setCount(count);
                list.add(vo);

                entry.setModel(vo.getModel());
                entry.setRemark(vo.getRemark());
                entry.setProductName(vo.getProductName());
                entry.setCategoryId(categoryId);
                entry.setTotalPrice(price.setScale(2, BigDecimal.ROUND_DOWN));
                entry.setQty(qtys);
                entry.setViceQty(viceQty.setScale(2, BigDecimal.ROUND_DOWN));
                entry.setCount(count);
                entry.setWriteAmount(BigDecimal.ZERO);
                entry.setWriteStatus("0");
                entries.add(entry);
            }
            if(order != null) {
            	if (StringUtils.isNotBlank(order.getExpressType())) {
                    printOrderVO.setHyType(order.getExpressType());
                    salesVo.setHyType(order.getExpressType());
                }
                if (StringUtils.isNotBlank(order.getPayType())) {
                    printOrderVO.setPayType(order.getPayType());
                }
            }
            totals = totals.add(total).setScale(2, BigDecimal.ROUND_HALF_UP);
            ioBill.setIsPrint(1);
            ioBillService.updateById(ioBill);
        }
        if (StringUtils.isNotBlank(printOrderVO.getHyType())) {
        	ZrkDeliveryMethod zrkDeliveryMethod = deliveryMethodService.getById(printOrderVO.getHyType());
            if(zrkDeliveryMethod!=null) {
            	printOrderVO.setHyType(zrkDeliveryMethod.getName());
            }
        }
        if (StringUtils.isNotBlank(printOrderVO.getPayType())) {
        	List<DictModel> modelList = sysBaseAPI.queryDictItemsByCode("sale_order_pay_type");
        	String payType = "";
        	if(modelList!=null&&modelList.size()>0) {
        		for(DictModel model:modelList) {
        			model.getValue();
        			if(model.getValue().equals(printOrderVO.getPayType())) {
        				payType = model.getText();
        			}
        		}
        	}
            printOrderVO.setPayType(payType);
        }
        printOrderVO.setTotalAmount(totals.toString());
        printOrderVO.setTotalBig(toChinese(totals.toString()));
        salesVo.setTotalAmount(totals);
        salesVo.setTotalBig(toChinese(totals.toString()));
        salesVo.setSalesType(0);
        printOrderVO.setList(list);
        if(StringUtils.isNotBlank(salesVo.getCustomerName())){
            deliveryService.saveMach(salesVo, entries, null);
        }
        printOrderVO.setCode(salesVo.getCode());

        return printOrderVO;
	}

	@Override
	@Transactional
	public PrintOrderVO DdIoBillPrint(String billId, String orderId) {
		StkIoBill bill = ioBillService.getById(billId);
		List<StkIoBill> ioBills = Lists.newArrayList();
		if(null != bill) {
			ioBills.add(bill);
		}
        PrintOrderVO printOrderVO = new PrintOrderVO();//打印vo
        SalesDelivery salesVo = new SalesDelivery();//出库信息保存vo
        List<PrintProductVO> list = CollUtil.newArrayList();
        List<SalesDeliveryEntry> entries = CollUtil.newArrayList();
        BigDecimal totals = new BigDecimal("0");
        List<ZrkOrderProduct> orderItemList = Lists.newArrayList();
        ZrkShoporder zrkShoporder = this.orderService.getById(orderId);
        Map<SalesDeliveryEntry, List<ZrkOrderProductMaterialLk>> maps = Maps.newHashMap();
        for (StkIoBill ioBill : ioBills) {
            BasCustomer customer = null;
            List<BasCustomerAddress> address = Lists.newArrayList();
            if (ioBill != null) {
                customer = customerService.getById(ioBill.getCustomerId());
            }
            LambdaQueryWrapper<StkIoBillEntry> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(StkIoBillEntry::getMid, ioBill.getId());
            List<StkIoBillEntry> billEntryList = stkIoBillService.list(wrapper);
            if(null == billEntryList) {
            	billEntryList = Lists.newArrayList();
            }
            if(zrkShoporder != null) {
            	salesVo.setSourceCode(zrkShoporder.getOrderNo());
            }
            
            if (customer != null) {
                address = customerAddressService.selectAddressByCustomerId(customer.getId());
            }
            if(null == customer) {
            	customer = new BasCustomer();
            }
            BasCustomer customer1 = customerService.getById("1318447754322341890");//查询到启元的公司信息
            BigDecimal total = BigDecimal.ZERO;
//            ZrkShoporder zrkShoporder = orderService.selectByOrderCode(ioBill.getSourceNo());
//            List<ZrkOrderProduct> zrkOrderProduct = productService.selectByMainId(zrkShoporder.getId());
            if (address != null && !address.isEmpty()) {
                printOrderVO.setCustomerAddress(address.get(0).getAddress());
                printOrderVO.setCustomerPhone(address.get(0).getPhoneNo());
                salesVo.setCustomerAddress(address.get(0).getAddress());
                salesVo.setCustomerPhone(address.get(0).getPhoneNo());
            }
            if(null != zrkShoporder) {
            	printOrderVO.setCustomerPhone(zrkShoporder.getCustomerMobile());
            	if(StringUtils.isNotBlank(zrkShoporder.getCustomerAddress())) {
            		printOrderVO.setCustomerAddress(zrkShoporder.getCustomerAddress());
            	}
            	printOrderVO.setCode(zrkShoporder.getOrderNo());
            }
            printOrderVO.setCustomerName(customer.getName());
            printOrderVO.setDateString(DateUtils.formatDate(new Date(), "yyyy/MM/dd"));
            printOrderVO.setSelfAddress(customer1.getAddress());
            printOrderVO.setSelfPhone(customer1.getCorporatePhone());

            salesVo.setCompanyId(customer1.getId());
            salesVo.setCustomerName(customer.getName());
            salesVo.setCustomerId(customer.getId());
            salesVo.setShippingDate(new Date());
            salesVo.setSelfAddress(customer1.getAddress());
            salesVo.setSelfPhone(customer1.getCorporatePhone());
//            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//            printOrderVO.setMaker(sysUser.getRealname());
//            salesVo.setMaker(sysUser.getRealname());
            /***********测试用***********/
//            printOrderVO.setMaker("admin");
//            salesVo.setMaker("admin");
            /*****************/
            Map<PrintProductVO, List<BasMaterial>> map = Maps.newHashMap();
            Map<String, StkIoBillEntry> entryMap = Maps.newHashMap();
            List<String> materialIdList = Lists.newArrayList(UUID.randomUUID().toString());
            for (StkIoBillEntry stkIoBill : billEntryList) {
            	materialIdList.add(stkIoBill.getMaterialId());
                PrintProductVO vo = new PrintProductVO();//打印vo
                String materialId = stkIoBill.getMaterialId();
                BasMaterial basMaterial = materialService.getById(materialId);
                vo.setProductName(basMaterial.getName());
                String[] s = basMaterial.getModel().split("\\*");
                StringBuffer str = new StringBuffer(StringUtils.EMPTY);
                if(s.length > 1) {
                	String l = new BigDecimal(s[0]).stripTrailingZeros().toPlainString();
                    String w = new BigDecimal(s[1]).stripTrailingZeros().toPlainString();
                    str.append(l);
                    str.append("*");
                    str.append(w);
                } else {
                	String l = new BigDecimal(s[0]).stripTrailingZeros().toPlainString();
                	str.append(l);
                }
                BigDecimal unitPrice = stkIoBill.getSettlePrice();
                if (null != unitPrice) {
                    vo.setUnitPrice(unitPrice.setScale(2, BigDecimal.ROUND_DOWN).toString());
                }
                vo.setModel(str.toString());
                vo.setRemark(stkIoBill.getRemark());
                if (map.get(vo) == null) {
                    List<BasMaterial> basMaterials = Lists.newArrayList();
                    basMaterials.add(basMaterial);
                    map.put(vo, basMaterials);
                } else {
                    map.get(vo).add(basMaterial);
                }
                entryMap.put(materialId, stkIoBill);
            }
            Map<String, ZrkOrderProductMaterialLk> lkMap = Maps.newHashMap();
            if(materialIdList!=null && materialIdList.size()>0) {
            	LambdaQueryWrapper<ZrkOrderProductMaterialLk> q = new LambdaQueryWrapper<>();
            	q.in(ZrkOrderProductMaterialLk::getMaterialId, materialIdList);
            	List<ZrkOrderProductMaterialLk> lkList = this.productMateiralLkService.list(q);
                for (ZrkOrderProductMaterialLk lk : lkList) {
                	lkMap.put(lk.getMaterialId(), lk);
    			}
            }
            Map<String, BasMaterialTemp> tempMap = Maps.newHashMap();
            for (PrintProductVO vo : map.keySet()) {
                SalesDeliveryEntry entry = new SalesDeliveryEntry();//
                List<BasMaterial> basMaterials = map.get(vo);
                List<String> materialCodeList = Lists.newArrayList(UUID.randomUUID().toString());
                if(CollUtil.isNotEmpty(basMaterials)) {
                	for(BasMaterial material : basMaterials) {
                		materialCodeList.add(material.getCode());
                	}
                }
                List<BasMaterialTemp> tempList = tempService.getByCodes(materialCodeList);
                for (BasMaterialTemp temp : tempList) {
					tempMap.put(temp.getCode(), temp);
				}
                BigDecimal price = BigDecimal.ZERO;
                BigDecimal viceQty = BigDecimal.ZERO;
                BigDecimal qtys = BigDecimal.ZERO;
                Integer count = 0;
                String categoryId="";
                List<ZrkOrderProductMaterialLk> materialLkList = Lists.newArrayList();
                for (int i = 0; i < basMaterials.size(); i++) {
                    BasMaterial material = basMaterials.get(i);
                    materialLkList.add(lkMap.get(material.getId()));
                    categoryId=material.getCategoryId();
                    String materialId = material.getId();
                    StkIoBillEntry stkIoBillEntry = entryMap.get(materialId);
                    BigDecimal totalPrice = stkIoBillEntry.getSettleAmt();
                    if (null != totalPrice) {
                        price = price.add(totalPrice);
                        vo.setTotalPrice(totalPrice);
                        entry.setTotalPrice(totalPrice);
                        total = total.add(totalPrice);
                    }
                    BigDecimal unitPrice = stkIoBillEntry.getSettlePrice();
                    if (null != unitPrice) {
                        vo.setUnitPrice(unitPrice.setScale(2, BigDecimal.ROUND_DOWN).toString());
                        entry.setUnitPrice(unitPrice.setScale(2, BigDecimal.ROUND_DOWN).toString());
                    }
                    BigDecimal vqty = basMaterials.get(i).getViceQuantity();
                    viceQty = viceQty.add(vqty);
                    vo.setViceQty(basMaterials.get(i).getViceQuantity().setScale(0, BigDecimal.ROUND_DOWN));
                    String unitId = basMaterials.get(i).getUnitId();
                    if (StringUtils.isNotBlank(unitId)) {
                        BasMeasureUnit unit = this.unitService.getById(unitId);
                        if (null != unit) {
                            vo.setUnit(unit.getName());
                            entry.setUnit(unit.getName());
                        }
                    }
                    BasMaterialTemp temp = tempMap.get(material.getCode());
                    String processId = null;
                    if(null != temp) {
                    	String procedureId = temp.getProcedureId();
                    	if(StringUtils.isNotBlank(procedureId)) {
                    		ZrkQzOrder mes = this.mesService.getById(procedureId);
                    		if(null != mes) {
                    			processId = mes.getProcessId();
                    		}
                    	}
                    }
                    
//                    if (zrkOrderProduct != null && zrkOrderProduct.size() > 0) {
//                        processId = zrkOrderProduct.get(0).getProcessId();
//                    }
                    if (MaterialConstant.PROCESS_COMPOUND.equals(processId)) {
                        vo.setViceUnit("卷");
                        entry.setViceUnit("卷");
                    }
                    if (MaterialConstant.PROCESS_PART.equals(processId)) {
                        vo.setViceUnit("卷");
                        entry.setViceUnit("卷");
                    }
                    if (MaterialConstant.PROCESS_CUTTING_BIG.equals(processId) || MaterialConstant.PROCESS_CUTTING_NORMAL.equals(processId)) {
                        vo.setViceUnit("张");
                        entry.setViceUnit("张");
                    }
                    if(null == processId) {
                    	vo.setViceUnit("卷");
                        entry.setViceUnit("卷");
                    }
                    BigDecimal inventoryQty = stkIoBillEntry.getSettleQty();
                    if (!inventoryQty.equals(BigDecimal.ZERO)) {
                        qtys = qtys.add(inventoryQty);
                    }
                    ++count;
                }

                vo.setTotalPrice(price.setScale(2, BigDecimal.ROUND_DOWN));
                vo.setQty(qtys);
                vo.setViceQty(viceQty.setScale(2, BigDecimal.ROUND_DOWN));
                vo.setCount(count);
                list.add(vo);

                entry.setModel(vo.getModel());
                entry.setRemark(vo.getRemark());
                entry.setProductName(vo.getProductName());
                entry.setCategoryId(categoryId);
                entry.setTotalPrice(price.setScale(2, BigDecimal.ROUND_DOWN));
                entry.setQty(qtys);
                entry.setViceQty(viceQty.setScale(2, BigDecimal.ROUND_DOWN));
                entry.setCount(count);
                entry.setWriteAmount(BigDecimal.ZERO);
                entry.setWriteStatus("0");
                entries.add(entry);
                maps.put(entry, materialLkList);
            }
            if(zrkShoporder != null) {
            	if (StringUtils.isNotBlank(zrkShoporder.getExpressType())) {
                    printOrderVO.setHyType(zrkShoporder.getExpressType());
                    salesVo.setHyType(zrkShoporder.getExpressType());
                }
                if (StringUtils.isNotBlank(zrkShoporder.getPayType())) {
                    printOrderVO.setPayType(zrkShoporder.getPayType());
                }
            }
            totals = totals.add(total).setScale(2, BigDecimal.ROUND_HALF_UP);
            ioBill.setIsPrint(1);
            ioBillService.updateById(ioBill);
        }
        if (StringUtils.isNotBlank(printOrderVO.getHyType())) {
        	ZrkDeliveryMethod zrkDeliveryMethod = deliveryMethodService.getById(printOrderVO.getHyType());
            if(zrkDeliveryMethod!=null) {
            	printOrderVO.setHyType(zrkDeliveryMethod.getName());
            }
        }
        if (StringUtils.isNotBlank(printOrderVO.getPayType())) {
        	List<DictModel> modelList = sysBaseAPI.queryDictItemsByCode("sale_order_pay_type");
        	String payType = "";
        	if(modelList!=null&&modelList.size()>0) {
        		for(DictModel model:modelList) {
        			model.getValue();
        			if(model.getValue().equals(printOrderVO.getPayType())) {
        				payType = model.getText();
        			}
        		}
        	}
            printOrderVO.setPayType(payType);
        }
        printOrderVO.setTotalAmount(totals.toString());
        printOrderVO.setTotalBig(toChinese(totals.toString()));
        salesVo.setTotalAmount(totals);
        salesVo.setTotalBig(toChinese(totals.toString()));
        salesVo.setSalesType(0);
        printOrderVO.setList(list);
        if(StringUtils.isNotBlank(salesVo.getCustomerName())){
            deliveryService.saveMach(salesVo, entries, maps);
        }
        printOrderVO.setCode(salesVo.getCode());

        return printOrderVO;
	}
}
